// 冷量过往排行
var numberFormate = iot.getNumberFormat("0");
var timeNotYearFormatMap = {
    'year': "%Y",
    'month': "%m",
    'day': "%m-%d",
    'hour': "%m-%d %H"
};
dev.action = function(resp,param){
    //获取工厂名称
    var factoryName = getFactoryName(param.workSpaceName);
    //是否算总还是单
    var totalOrSingle = param.selectType;
    if (totalOrSingle == null){
        totalOrSingle = "total";
    }
    var theTime = param.time;
    var workSpace = param.workSpace;
    var size = param.size;
    var page = param.page;
    var db = iot.db();
    var format;
    var resultData = {
        content : iot.list(),
        size : size,
        totalElements : 0,
        totalPages : 0
    };

    var theTimeNotYear =  '';
    if(theTime && theTime.length() > 4){
        theTimeNotYear = theTime.substring(5,theTime.length());
    }
    var timeType = iot.getTimeByFormat(theTime);
    var timeDataList = getNearlyFourYears(param.time);
    format = timeNotYearFormatMap[timeType];
    var yieldId = getFactoryYieldId(factoryName)
    var airResult = db.qry("select DATE_FORMAT(dev_win.the_time,'%Y') yearIx, SUM(dev_win.dvalue) totalSum" +
        " from iot_dev_data_win dev_win, (select * from energy_struc_prop where type = 1 and field_type = '用量' and energy_struc_id = "+ workSpace +") esp" +
        " where dev_win.dev_id = esp.dev_id and dev_win.data_type = esp.name" +
        " and DATE_FORMAT(dev_win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'" +
        " group by yearIx" +
        " ORDER BY totalSum DESC");

    var resultCount = db.qry("select count(1) count from (select DATE_FORMAT(dev_win.the_time,'%Y') yearIx from iot_dev_data_win dev_win," +
        " (select * from energy_struc_prop where type = 1 and field_type = '用量' and energy_struc_id = "+ workSpace +") esp" +
        " where dev_win.dev_id = esp.dev_id and dev_win.data_type = esp.name" +
        " and DATE_FORMAT(dev_win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'" +
        " group by yearIx)a");

    var yieldResult = db.qry("select DATE_FORMAT(win.the_time,'%Y') yearIx,SUM(dvalue) totalSum \n" +
        "from iot_dev_data_win win\n" +
        "where dev_id = "+ yieldId +" \n" +
        "and DATE_FORMAT(win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'\n" +
        "group by yearIx ORDER BY totalSum DESC");
    var resultList = iot.list();

    var count = 0;
    var preValue = "";
    var totalSum = 0;
    var totalYield = 0;
    // 开始组装数据
    airResult.forAll(function (item) {
        // 只有数值不一样，排名才会上升，将当前值赋值给preValue
        if (!item.totalSum.equals(preValue)) {
            preValue = item.totalSum;
            ++count;
        }
        totalSum = item.totalSum;
        yieldResult.forAll(function (yieldItem) {
            if (item.yearIx.equals(yieldItem.yearIx)) {
                totalYield = yieldItem.totalSum;

            }
        });
        //判断当前选择总数还是单车
        if (totalOrSingle.equals("single")) {
            if (totalYield){
                totalSum = totalSum/totalYield;
            }
            if (totalYield === 0){
                totalSum = 0;
            }
        }
        resultList.add({rank: count, year: item.yearIx, useNum: numberFormate.format(totalSum), increase: "0%"});
    })
    // 如果没有timeDataList年份的数据，则赋值为0
    for (var i in timeDataList) {
        var flag = false;
        for (var key in resultList) {
            if (resultList[key].year.equals(timeDataList[i])) {
                flag = true;
            }
        }
        if (!flag) {
            resultList.add({rank: count + 1, year: timeDataList[i], useNum: 0, increase: "0%"});
        }
    }
    // 计算同比年/月/日涨幅
    var increaseList = iot.list();
    for (var i in timeDataList) {
        if (i == 0) {
            continue;
        }
        var currentUseNum = 0, preUseNum = 0; // 存储当前年份总量和同比时间的总量
        for (var j in resultList) {
            if (timeDataList[i].equals(resultList[j].year)) {
                currentUseNum = resultList[j].useNum;
            }
            if (timeDataList[i - 1].equals(resultList[j].year)) {
                preUseNum = resultList[j].useNum;
            }
        }
        if (currentUseNum == 0 || preUseNum == 0) { // 只要有一年的总量为0，则计算涨幅没有意义
            continue;
        }
        var increase = (currentUseNum - preUseNum) / preUseNum; // 计算同比涨幅
        var toFixedIncrease = (100 * increase).toFixed(2); // 保留两位小数
        increaseList.add({year: timeDataList[i], increase: toFixedIncrease + "%"})
    }

    // 修改同比涨幅
    for (var i in resultList) {
        // 开始遍历修改resultList的同比涨幅increase
        var flag = false;
        var increase;
        for (var j in increaseList) {
            if (resultList[i].year.equals(increaseList[j].year)) {
                flag = true;
                increase = increaseList[j].increase;
            }
        }
        if (flag) {
            resultList[i].increase = increase;
        }
    }
    /*// 时间格式转换成和theTime一样
    for (var i in resultList) {
        resultList[i].year = getTime(resultList[i].year, theTime);
    }*/
    resultData.content = resultList;
    resultData.size = airResult.getValue().size();
    resultData.totalElements = resultCount.getValue().count;
    resultData.totalPages = parseInt(resultData.totalElements / size);

    resp.setJsData(resultData);
}